package cn.tjad.tjad2.module.notice.settings.fragment;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.baozi.treerecyclerview.adpater.TreeRecyclerAdapter;
import com.baozi.treerecyclerview.adpater.TreeRecyclerType;
import com.baozi.treerecyclerview.factory.ItemHelperFactory;
import com.baozi.treerecyclerview.item.TreeItem;
import com.qiandian.android.base.common.bean.BaseBean;
import com.qiandian.android.base.common.bean.CommonBean;
import com.qiandian.android.base.fragment.BaseFragment;
import com.qiandian.android.base.widget.TJADTTitleView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.List;

import butterknife.BindView;
import cn.tjad.tjad2.R;
import cn.tjad.tjad2.consts.Keys;
import cn.tjad.tjad2.data.bean.NoticeSetting;
import cn.tjad.tjad2.data.bean.NoticeSettingElement;
import cn.tjad.tjad2.data.bean.NoticeSettingGroup;
import cn.tjad.tjad2.data.event.NoticeSwitchEvent;
import cn.tjad.tjad2.module.notice.settings.adapter.NoticeSettingGroupItem;
import cn.tjad.tjad2.module.notice.settings.bean.UpDateNoticeSettingRequestBean;
import cn.tjad.tjad2.net.http.ResponseObserver;
import cn.tjad.tjad2.net.http.RetrofitManager;
import cn.tjad.tjad2.route.PageId;
import cn.tjad.tjad2.utils.RxUtils;
import cn.tjad.tjad2.utils.Tools;
import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.functions.Action;
import io.reactivex.functions.Function;

@Route(path = PageId.MESSAGE_SETTINGS)
public class NoticeSettingFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener {

    @BindView(R.id.swipe_refresh_layout)
    protected SwipeRefreshLayout swipeRefreshLayout;
    @BindView(R.id.recyclerview)
    protected RecyclerView recyclerView;
    private TreeRecyclerAdapter treeRecyclerAdapter;

    private int noticeType = 1;
    private String noticeTypeName = null;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        Bundle bundle = getArguments();
        if (bundle != null) {
            noticeType = bundle.getInt(Keys.MESSAGE_TYPE);
            noticeTypeName = bundle.getString(Keys.MESSAGE_TYPE_NAME);
        }
    }

    @Override
    public View getContentView(LayoutInflater inflater) {
        return inflater.inflate(R.layout.common_recylerview, null);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = super.onCreateView(inflater, container, savedInstanceState);
        swipeRefreshLayout.setEnabled(true);
        swipeRefreshLayout.setOnRefreshListener(this);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.addItemDecoration(new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL));
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        treeRecyclerAdapter = new TreeRecyclerAdapter(TreeRecyclerType.SHOW_EXPAND);
        recyclerView.setAdapter(treeRecyclerAdapter);
        requestSettingItems();
    }

    @Override
    protected void setCustomerTitle(TJADTTitleView titleView) {
        super.setCustomerTitle(titleView);
        titleView.setCenterText(noticeTypeName);
    }

    @Override
    public void onRefresh() {
        requestSettingItems();
    }

    private void requestSettingItems() {
        RetrofitManager.getInstance().getApiService()
                .getUserSettings()
                .compose(RxUtils.networkTransformer())
                .subscribe(new ResponseObserver<NoticeSetting>(compositeDisposable) {
                    @Override
                    public void onSuccess(CommonBean<NoticeSetting> t) {
                        onNoticeInfoGet(t.result);
                        swipeRefreshLayout.setRefreshing(false);
                    }

                    @Override
                    public void onFailed(String message) {
                        Tools.showToast(message);
                        swipeRefreshLayout.setRefreshing(false);
                    }
                });
    }

    private void onNoticeInfoGet(NoticeSetting result) {
        if (result != null && result.message != null && !result.message.isEmpty()) {
            Observable.fromIterable(result.message)
                    .doOnNext(it -> it.noticeType = noticeType)
                    .flatMap((Function<NoticeSettingGroup, ObservableSource<NoticeSettingElement>>) it -> Observable.fromIterable(it.settings))
                    .doOnNext(it -> {
                        it.noticeType = noticeType;
                    })
                    .doOnComplete(new Action() {
                        @Override
                        public void run() throws Exception {
                            List<TreeItem> items = ItemHelperFactory.createItems(result.message, NoticeSettingGroupItem.class, null);
                            treeRecyclerAdapter.getItemManager().replaceAllItem(items);
                        }
                    })
                    .subscribe();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    //来自item中的开关切换事件
    @Subscribe
    public void onSwitchCheckChanged(NoticeSwitchEvent event) {
        if (event == null) {
            return;
        }
        UpDateNoticeSettingRequestBean bean = new UpDateNoticeSettingRequestBean();
        NoticeSettingElement data = event.getNoticeSettingElement();
        bean.type = data.type;
        bean.appPush = data.appPush;
        bean.email = data.email;
        bean.message = data.message;
        bean.popupWin = data.popupWin;
        bean.sms = data.sms;
        bean.setSwitch(noticeType, event.isChecked());
        RetrofitManager.getInstance().getApiService()
                .updateSettings(bean)
                .compose(RxUtils.networkTransformer())
                .subscribe(new ResponseObserver<BaseBean>(compositeDisposable) {
                    @Override
                    public void onSuccess(CommonBean<BaseBean> t) {
                        Tools.showToast("设置成功");
                        data.setChecked(event.isChecked());
                    }

                    @Override
                    public void onFailed(String message) {
                        Tools.showToast("设置失败");
                        treeRecyclerAdapter.notifyItemChanged(event.getPosition());
                    }
                });
    }
}
